package com.springfairytale.qqserver.action;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.springfairytale.qq.common.Constant;
import com.springfairytale.qq.common.Protocol;
import com.springfairytale.qqserver.entity.Friend;
import com.springfairytale.qqserver.entity.User;
import com.springfairytale.qqserver.main.Context;

public class LoginAction extends BaseAction {

	@Override
	public void execute() {

		// 获取从Client端传过来的信息
		Map<String, Object> fromMsg = p.getMsg();
		String uid = (String) fromMsg.get("who");
		String pwd = (String) fromMsg.get("pwd");

		Protocol reProtocol = new Protocol();
		Map<String, Object> toMsg = new HashMap<>();

		User u = Context.usersInfo.get(uid); // 获取到登录用户的信息
		

		Map<String, User> uFriend = new HashMap<>();//获取所有好友
		uFriend = Context.usersInfo;
		Set<Friend> friends = new HashSet<>();

		for (User v : uFriend.values()) {
			if (!v.getUid().equals(uid)) {
				Friend friend = new Friend(v.getUid(), v.getNickname(), v.getPic(), v.getSex(), v.getSignature(),v.getState());
				friends.add(friend);
			}
		}
//		 for(Friend f:friends){
//		 System.out.println(f.);
//		 }

		if (u != null && pwd.equals(u.getPassword())) {
			Context.sockets.put(uid, s);
			reProtocol.setAction(Constant.LOGIN_RESULT);
			u.setState(1);
			toMsg.put("result", "succ");
			toMsg.put("userinfo", u);
			toMsg.put("friends", friends);
			List<Map<String, Object>> chatContentList = Context.chatContentMap.get(uid);
//			if (chatContentList!=null&&(!chatContentList.isEmpty())) {
//				toMsg.put("newMessage", chatContentList);
//			}
			if (chatContentList!=null) {
				toMsg.put("newMessage", chatContentList);
			}
			reProtocol.setMsg(toMsg);
		} else {
			reProtocol.setAction(Constant.LOGIN_RESULT);
			toMsg.put("result", "fail");
			reProtocol.setMsg(toMsg);
		}
		reProtocol.sendMessage(s);
		if (Context.chatContentMap.get(uid)!=null) {
			Context.chatContentMap.get(uid).clear();
		}
		
	}

}
